package com.centriole.service.workflow.service.impl;

import com.centriole.service.workflow.dao.InstanceHistoryMapper;
import com.centriole.service.workflow.dao.ProNodeMapper;
import com.centriole.service.workflow.entity.InstanceHistory;
import com.centriole.service.workflow.enums.CancelTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.TaskServiceImpl;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 功    能：上步撤回
 * 创建人：王鑫
 * 时    间：2018年1月5日下午3:18:15
 */

@Service
public class FlowTraceService {
	
	@Resource
	private HistoryService historyService;
	@Resource
	private InstanceHistoryMapper instanceHistoryMapper;
	@Resource
	private TaskService taskService;
	@Resource
	private RuntimeService runtimeService;
	@Resource
	private ProNodeMapper proNodeMapper;
	
	public CancelTask useCancelTask(String instanceId, String taskName) {
		 //region 判断此任务是不是实例中最后一个完成的任务，即如果下一个任务已完成，此时不能进行撤销操作
        HistoricProcessInstance historicInstance = historyService
                .createHistoricProcessInstanceQuery().unfinished()
                .processInstanceId(instanceId).singleResult();
        //流程完成了不能撤销任务
        if (historicInstance == null)
            return CancelTask.PROCESS_END;
 
        List<InstanceHistory> historyList = instanceHistoryMapper.selectByInstanceIdOderByDesc(instanceId);
        //最后一个完成任务已不是当前任务，不能撤销
        if (!taskName.equals(historyList.get(0).getTaskLogicalName()))
            return CancelTask.TASK_BE_EXE;

        //region 任务处于暂停阶段不能撤销
        List<Task> list = taskService.createTaskQuery()
                .processInstanceId(instanceId).suspended().list();
        if (list != null && list.size() > 0) {
            return CancelTask.TASK_SUSPEND;
        }
        //endregion
        //region 执行撤销
        TaskServiceImpl taskServiceImpl = (TaskServiceImpl) taskService;
        taskServiceImpl.getCommandExecutor().execute(new TaskCommitCmd(instanceId,historyList.get(0).getTaskNodeId()));
        String node=historyList.get(0).getTaskName().split("-")[0];
        instanceHistoryMapper.deleteByInstanceIdAndTaskName(instanceId,node);
        return CancelTask.SUCCESS;
        //endregion
    }
	}

